<!--
  @name: ToolSlotSensorBind
  @description: 工装插槽传感器绑定功能
-->

<template>
  <div>
    <el-row
      :gutter="20"
      v-for="(rowNum, rowIndex) in Math.ceil(slotCount / colCountInRow)"
      :key="rowIndex"
    >
      <el-col :span="4" v-for="(colNum, colIndex) in colCountInRow">
        <el-button
          circle
          gutter="5px"
          :key="rowIndex * 5 + colIndex + 1"
          v-if="rowIndex * 5 + colIndex + 1 <= slotCount"
          :disabled="isSelectedArray[rowIndex * 5 + colIndex + 1]"
          :type="isSelectedArray[rowIndex * 5 + colIndex + 1] ? 'info' : ''"
          @click="handleClick(rowIndex * 5 + colIndex + 1)"
        >
          {{ rowIndex * 5 + colIndex + 1 }}
        </el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
// 插槽数量
import { useSensorStore } from "@/store/business/sensor.store";
import systemApi from "@/api/system.api";

let slotCount = ref(10);
const colCountInRow = 5;

const sensorStore = useSensorStore();

const props = defineProps<{
  sensorInfo: SensorInfo;
}>();

onBeforeMount(() => {
  systemApi.getToolSlotCount().then((res) => {
    slotCount.value = res;
  });
});

const isSelectedArray = ref<boolean[]>([]);
watch(
  () => sensorStore.currentToolInfo?.sensors,
  (value) => {
    if (!value) return;
    for (let slotNum = 0; slotNum < slotCount.value + 1; slotNum++) {
      isSelectedArray.value[slotNum] = value.some((item) => item.slotNum === slotNum);
    }
  },
  { immediate: true, deep: true }
);

/**
 * 绑定插槽
 * @param slotNum 插槽编号
 */
function handleClick(slotNum: number) {
  const sensor = props.sensorInfo;
  sensor.slotNum = slotNum;
  sensorStore.addSelectedSensors(sensor);
}
</script>

<style scoped>
.el-row {
  margin-bottom: 10px;
}

.el-row:last-child {
  margin-bottom: 0;
}
</style>
